package com.chainyoung.component_tmperson.ui.activity.dapp;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;

import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chainyoung.common.appcommon.hdwallet.OwnWalletUtils;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.base.OtherAppBaseActivity;
import com.chainyoung.common.jsoup.interfaces.Text;
import com.chainyoung.common.mvp.BasePresenter;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.X5WebView;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.ui.activity.ScanQrCodeActivity;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;
import static com.chainyoung.common.constant.CommonStringConstants.URL;
import static com.chainyoung.common.constant.LibConstant.BROWSER_INDEX_URL;
import static com.chainyoung.common.utils.Utils.getContext;

public abstract class BaseBrowserActivity<P extends BasePresenter> extends BaseActivity<P> {


    protected FrameLayout frameLayout;
    protected X5WebView mWebView;
    protected ProgressBar mPageLoadingProgressBar = null;
    protected ImageView ivBack;
    protected EditText editText;
    protected ImageView ivRefresh;
    protected ImageView ivCollect;
    protected ImageView ivScan;
    protected ImageView ivBrowserBack;
    protected ImageView ivBrowserForward;
    protected TextView ivBrowserHome;
    protected TextView ivBrowserHistory;
    protected TextView ivBrowserCollections;
    protected TextView ivBrowserShare;

    protected boolean isLoading = true;//是否正在加载中
    protected boolean isCollected = false;//网页是否已收藏

    private android.webkit.ValueCallback<Uri> mUploadMessage;//回调图片选择，4.4以下
    private android.webkit.ValueCallback<Uri[]> mUploadCallbackAboveL;//回调图片选择，5.0以上
    private static final int FILE_SELECT_CODE = 0;

    protected String TAG = getClass().getSimpleName();

    protected String address = "";
    protected String url;
    String jsStr = "";
    String jsAppName = "const appname=\"cbob\";";

    protected String webTitle;

    protected final static int REQUEST_URL = 0x111;

    private X5WebView newWebView;

    private boolean isCanClearTitle;



    @Override
    protected void initUI() {
        initParams();
        initViews();
        initProgressBar();
        initSettings();
        initListeners();

    }



    private void initParams() {
        url = getIntent().getStringExtra(URL);
        try {
            InputStream in = mContext.getAssets().open("trust_min.js");
            byte buff[] = new byte[1024];
            ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
            do {
                int numRead = in.read(buff);
                if (numRead <= 0) {
                    break;
                }
                fromFile.write(buff, 0, numRead);
            } while (true);
            jsStr = fromFile.toString();
            // jsStr=jsStr+"\n"+trasanctionJs;
            in.close();
            fromFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initViews() {
        mWebView = new X5WebView(this, null);
        frameLayout = findViewById(R.id.fl_web);
        mPageLoadingProgressBar = findViewById(R.id.progressBar);
        ivBack = findViewById(com.chainyoung.common.R.id.iv_left_image);
        editText = findViewById(com.chainyoung.common.R.id.title);
        frameLayout.addView(mWebView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ivRefresh = findViewById(R.id.iv_refresh);
        ivCollect = findViewById(R.id.iv_collect);
        ivScan = findViewById(R.id.iv_scan);
        ivBrowserBack = findViewById(R.id.iv_browser_back);
        ivBrowserForward = findViewById(R.id.iv_browser_forward);
        ivBrowserHome = findViewById(R.id.iv_browser_home);
        ivBrowserHistory = findViewById(R.id.iv_browser_history);
        ivBrowserCollections = findViewById(R.id.iv_browser_collections);
        ivBrowserShare = findViewById(R.id.iv_browser_share);
        editText.clearFocus();
    }

    private void initListeners() {
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String url = editText.getText().toString().trim();
                    if (!url.isEmpty()) {
                        if (url.startsWith("http")) {
                            mWebView.loadUrl(url);
                        } else {
                            mWebView.loadUrl("http://" + url);
                        }
                    }
                    closeKeybord();
                    return false;
                }
                return false;
            }
        });

        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                ivRefresh.setImageResource(hasFocus ? R.mipmap.ic_browser_close : R.mipmap.ic_browser_refresh);
                //isCanClearTitle=hasFocus;
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //ivRefresh.setVisibility(TextUtils.isEmpty(s.toString())?View.GONE:View.VISIBLE);
                if (TextUtils.isEmpty(s.toString())) {
                    ivRefresh.setImageResource(R.mipmap.ic_browser_refresh);
                }
            }
        });
        ivBack.setOnClickListener(onClickListener);
        ivRefresh.setOnClickListener(onClickListener);
        ivCollect.setOnClickListener(onClickListener);
        ivScan.setOnClickListener(onClickListener);
        ivBrowserBack.setOnClickListener(onClickListener);
        ivBrowserForward.setOnClickListener(onClickListener);
        ivBrowserHome.setOnClickListener(onClickListener);
        ivBrowserHistory.setOnClickListener(onClickListener);
        ivBrowserCollections.setOnClickListener(onClickListener);
        ivBrowserShare.setOnClickListener(onClickListener);
        // editText.setOnClickListener(onClickListener);


    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.iv_left_image) {
                finish();
            } else if (v.getId() == R.id.iv_refresh) {
                if (editText.isFocused()) {
                    if (StringUtil.viewGetTextIsEmpty(editText)) {
                        mWebView.loadUrl(url);
                    } else {
                        editText.setText("");
                    }
                } else {
                    url = editText.getText().toString().trim();
                    mWebView.loadUrl(url);
                }
            } else if (v.getId() == R.id.iv_collect) {
                if (isCollected) {
                    //取消收藏
                    cancelCollect();
                } else {
                    //收藏
                    addCollect();
                }
            } else if (v.getId() == R.id.iv_scan) {
                launchForResult(ScanQrCodeActivity.class, REQUEST_URL);
            } else if (v.getId() == R.id.iv_browser_back) {
                if (mWebView.canGoBack()) {
                    if (newWebView != null) {
                        newWebView.destroy();
                    }
                    mWebView.goBack();
                }
            } else if (v.getId() == R.id.iv_browser_forward) {
                if (mWebView.canGoForward()) {
                    mWebView.goForward();
                }
            } else if (v.getId() == R.id.iv_browser_home) {
                url = BROWSER_INDEX_URL;
                mWebView.loadUrl(url);
            } else if (v.getId() == R.id.iv_browser_history) {
                launch(BrowserHistoryActivity.class);
            } else if (v.getId() == R.id.iv_browser_collections) {
                launch(BrowserCollectionActivity.class);
            } else if (v.getId() == R.id.iv_browser_share) {
                Intent share_intent = new Intent();
                share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
                share_intent.setType("text/plain");//设置分享内容的类型
                share_intent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());//添加分享内容标题
                share_intent.putExtra(Intent.EXTRA_TEXT, url);//添加分享内容
                //创建分享的Dialog
                share_intent = Intent.createChooser(share_intent, "分享到");
                startActivity(share_intent);
            } else if (v.getId() == R.id.title) {
                // ivRefresh.setImageResource(R.mipmap.ic_browser_close);
            }
        }
    };

    /**
     * 取消收藏
     */
    protected abstract void cancelCollect();

    /**
     * 添加收藏
     */
    protected abstract void addCollect();

    /**
     * 添加浏览记录
     */
    protected abstract void addBrowseCache();


    protected void setEditTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            editText.setText(title);
            editText.setSelection(title.length());
        }
    }

    private void initProgressBar() {
        mPageLoadingProgressBar.setMax(100);
        mPageLoadingProgressBar.setProgressDrawable(this.getResources()
                .getDrawable(R.drawable.color_progressbar));
    }

    private void initSettings() {
        mWebView.setSaveEnabled(true);
        mWebView.setKeepScreenOn(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        mWebView.addJavascriptInterface(new JavaScriptinterface(this),
                "android");


        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
                Uri uri = Uri.parse(s);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle = title;

            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                //return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
                newWebView = new X5WebView(view.getContext());
                X5WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                newWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        mWebView.loadUrl(String.valueOf(url));
                        return true;
                    }
                });
                transport.setWebView(newWebView);
                resultMsg.sendToTarget();
                return true;
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                mPageLoadingProgressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
                if (newProgress == 70) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        mWebView.evaluateJavascript(jsStr, new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {//js与native交互的回调函数
                                Log.d("webview", "value=" + value);
                            }
                        });
                    }

                }
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_SELECT_CODE);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILE_SELECT_CODE);
                return true;
            }


        });
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String ur) {
                super.onPageFinished(view, ur);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
                mPageLoadingProgressBar.setVisibility(View.GONE);
                ivRefresh.setImageResource(R.mipmap.ic_browser_refresh);
                isLoading = false;
                editText.setText(ur);
                editText.clearFocus();
                url = ur;
                ivBrowserBack.setImageResource(mWebView.canGoBack() ? R.mipmap.ic_browser_back_blue : R.mipmap.ic_browser_back_gray);
                ivBrowserForward.setImageResource(mWebView.canGoForward() ? R.mipmap.ic_browser_foward_blue : R.mipmap.ic_browser_foward_gray);
                //ivCollect.setImageResource(checkUrlIsCollected(ur) ? R.mipmap.ic_browser_collected : R.mipmap.ic_browser_collect_no);
                //isCollected = checkUrlIsCollected(ur);
                //view.loadUrl("javascript: var allLinks = document.getElementsByTagName('a'); if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];var target = link.getAttribute('target'); if (target && target == '_blank') {link.href = 'newtab:'+link.href;link.setAttribute('target','_self');}}}");
                checkUrlIsCollected(ur);
                addBrowseCache();

                //mWebView.loadUrl("javascript:" + jsStr);
                /*if (Build.VERSION.SDK_INT >= 19) {
                    mWebView.evaluateJavascript(jsStr, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {//js与native交互的回调函数
                            Log.d("webview", "value=" + value);
                        }
                    });
                }*/


            }


            @Override
            public void onPageStarted(WebView view, String ur, Bitmap favicon) {

                mPageLoadingProgressBar.setVisibility(View.VISIBLE);
                ivRefresh.setImageResource(R.mipmap.ic_browser_close);
                isLoading = true;
                editText.setText(ur);
                super.onPageStarted(view, ur, favicon);
                if (Build.VERSION.SDK_INT >= 19) {
                    mWebView.evaluateJavascript(jsAppName, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {//js与native交互的回调函数
                            Log.d("webview", "value=" + value);
                        }
                    });
                }
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("newtab:")) {
                    view.loadUrl(url.replace("newtab:", ""));
                    return false;
                } else if ((url.startsWith("http:") || url.startsWith("https:"))) {
                    view.loadUrl(url);
                    editText.setText(url);
                    return false;
                }
                return true;
            }
        });


        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }


    }

    /**
     * url 是否被收藏
     *
     * @param url
     */
    protected void checkUrlIsCollected(String url) {

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG, "onKeyDown: keyCode -- " + keyCode);
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (mWebView.canGoBack()) {
                    //表示按返回键时的操作
                    mWebView.loadUrl("javascript:executeCallback(8888,\"canceled\",null)");
                    if (newWebView != null) {
                        newWebView.destroy();
                    }
                    mWebView.goBack();   //后退
                    return true;    //已处理
                } else {
                    if (newWebView != null) {
                        newWebView.destroy();
                    }
                    finish();
                    return true;
                }
            }
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void onFinish() {
            finish();
        }

        @JavascriptInterface
        public void signTransaction(String transactionInfo) {
            getWebTransactionInfo(transactionInfo);
        }

        @JavascriptInterface
        public void signMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public void signPersonalMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public void signTypedMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public String setAddr() {
            return address;
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            if (requestCode != REQUEST_URL) {
                if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                    mUploadCallbackAboveL.onReceiveValue(null);//回调给js
                } else {
                    //4.4以下处理
                    mUploadMessage.onReceiveValue(null);
                }
                return;
            } else {
                return;
            }
        }

        switch (requestCode) {
            case FILE_SELECT_CODE: {
                if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                    Uri uri = data.getData();
                    Uri[] uris = new Uri[]{uri};
                   /* ClipData clipData = data.getClipData();  //选择多张
                    if (clipData != null) {
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            Uri uri = item.getUri();
                            uris[i]=uri;
                        }
                    }*/
                    mUploadCallbackAboveL.onReceiveValue(uris);//回调给js
                } else {//4.4以下处理
                    Uri uri = data.getData();
                    mUploadMessage.onReceiveValue(uri);
                }


            }
            break;
            case REQUEST_URL:
                String result = data.getStringExtra("data");
                editText.setText(result);
                mWebView.loadUrl(result);
                break;
        }
    }

    /**
     * 获取到Dapp 交易数据
     *
     * @param transactionInfo
     */
    protected void getWebTransactionInfo(String transactionInfo) {


    }


    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_browser;
    }


    @Override
    protected void onResume() {
        super.onResume();
        checkUrlIsCollected(url);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null)
            mWebView.destroy();

    }

    /**
     * 关闭软键盘
     */
    public void closeKeybord() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }




}
